<?php
class db extends DBconfig {
	//保存连接的内部变量
	private static $db = array();
	//不允许克隆或技巧化
	final private function __construct() { }
	final private function __clone() { }

	//连接数据库
	public static function connect($DBkey=false) {
		$DBkey = is_bool($DBkey) ? parent::$DBDefault : $DBkey;//没有设置DBkey情况下使用默认DBkey
		if(!isset(parent::$DBlist[$DBkey])) {
			throw new Exception("Unknown DSN: $DBkey");
		}
		//如果连接不存在，则进行连接
		if (!isset(self::$db[$DBkey])) {
			if(is_array(parent::$DBlist[$DBkey])){
				try {
					$c = new ReflectionClass('PDO');
					self::$db[$DBkey] = $c->newInstanceArgs(parent::$DBlist[$DBkey]);
				} catch (Exception $e) {die("数据库连接失败: " . $e->getMessage());}
			} else {
				try {
					self::$db[$DBkey] = new PDO(parent::$DBlist[$DBkey]);
				} catch (Exception $e) {die("数据库连接失败: " . $e->getMessage());}
			}
		}
		//返回连接
		return self::$db[$DBkey];
	}
}


##数据库配置##
define('DBTP', 'p_');//表前缀
class DBconfig {
	//默认数据库
	protected static $DBDefault = "main";
	//数据库列表
	protected static $DBlist = array(
		'main' => array("mysql:charset=utf8;host=localhost;dbname=develop_ac", "root", "admin",array(PDO::ATTR_EMULATE_PREPARES => false))
	);
}